﻿using System.Security.Cryptography;
using System.Text;
using static JMBox.Config.R;

namespace JMBox.Utils
{
    public class SymmetricEncryptionTool
    {

        /// <summary>
        /// 3DES加密算法
        /// </summary>
        /// <param name="strContent">要加密的文本</param>
        /// <param name="strKey">对称密钥</param>
        /// <param name="encoding">编码方式，默认default</param>
        /// <returns></returns>
        public static string T_DESEEncrypt(string strContent, string strKey, Encoding encoding)
        {
            TripleDESCryptoServiceProvider DES = new TripleDESCryptoServiceProvider();
            MD5CryptoServiceProvider hashMD5 = new MD5CryptoServiceProvider();
            DES.Key = hashMD5.ComputeHash(encoding.GetBytes(strKey));
            DES.Mode = CipherMode.ECB;
            //创建加密器
            ICryptoTransform DESEncrypt = DES.CreateEncryptor();
            byte[] Buffer = encoding.GetBytes(strContent);
            //转为64为的字符串
            return Convert.ToBase64String(DESEncrypt.TransformFinalBlock(Buffer, 0, Buffer.Length));
        }

        /// <summary>
        /// 3DES解密
        /// </summary>
        /// <param name="strContent">被加密文本</param>
        /// <param name="strKey">加密秘钥</param>
        /// <param name="encoding">编码方式</param>
        /// <returns></returns>
        public static string T_DESDecrypt(string strContent, string strKey, Encoding encoding)
        {
            TripleDESCryptoServiceProvider DES = new TripleDESCryptoServiceProvider();
            MD5CryptoServiceProvider hashMD5 = new MD5CryptoServiceProvider();

            DES.Key = hashMD5.ComputeHash(encoding.GetBytes(strKey));
            DES.Mode = CipherMode.ECB;
            ICryptoTransform DESEncrypt = DES.CreateDecryptor();
            byte[] Buffer = Convert.FromBase64String(strContent);
            return encoding.GetString(DESEncrypt.TransformFinalBlock(Buffer, 0, Buffer.Length));
        }

        public static string getEncrypt(string plainText)
        {
            return SymmetricEncryptionTool.T_DESEEncrypt(plainText, Contact.SALT_PASSWORD, Encoding.UTF8);
        }

        public static string getDecrypt(string cryptText)
        {
            return SymmetricEncryptionTool.T_DESDecrypt(cryptText, Contact.SALT_PASSWORD, Encoding.UTF8);
        }
    }
}
